package cmd

import (
	"context"
	"fmt"
	"github.com/spf13/cobra"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"strings"
	"time"
)

// service名称
var serviceGetName string

func init() {
	// 获取 Service 的选项参数
	serviceGetCmd.Flags().StringVar(&serviceGetName, "name", "", "service name")
}

// Service 命令
var serviceRootCmd = cobra.Command{
	Use:     "service",
	Aliases: []string{"svc"},
	Short:   "service is used to manage kubernetes Services",
}

// Service Get 命令
var serviceGetCmd = cobra.Command{
	Use:   "get",
	Short: "get service or service list",
	Run: func(cmd *cobra.Command, args []string) {
		if namespace == "" {
			cmd.Help()
			return
		}

		// 创建 Kubernetes 客户端对象
		k8sClient, err := createK8SClient()
		if err != nil {
			fmt.Println("Err:", err)
			return
		}

		// 根据 serviceGetName 参数是否为空来决定显示单个 Service 信息还是所有 Service 信息
		listOption := metav1.ListOptions{}
		// 如果指定了 Service Name，那么只获取单个 Service 的信息
		if serviceGetName != "" {
			listOption.FieldSelector = fmt.Sprintf("metadata.name=%s", serviceGetName)
		}

		// 调用 List 接口获取 Service 列表
		serviceList, err := k8sClient.CoreV1().Services(namespace).List(context.Background(), listOption)
		if err != nil {
			fmt.Println("Err:", err)
			return
		}

		// 遍历 Service List，显示 Service 信息
		printFmt := "%-10s\t%-10s\t%-10s\t%-10s\t%-10s\t%-10s\n"
		fmt.Printf(printFmt, "NAME", "TYPE", "CLUSTER-IP", "EXTERNAL-IP", "PORT(S)", "AGE")
		for _, service := range serviceList.Items {
			// 格式化 ServicePort
			servicePorts := make([]string, 0, len(service.Spec.Ports))
			for _, p := range service.Spec.Ports {
				servicePorts = append(servicePorts, fmt.Sprintf("%d:%d/%s", p.Port, p.NodePort, p.Protocol))
			}

			// 格式化 External IPs
			externalIPs := make([]string, 0, len(service.Spec.ExternalIPs))
			for _, ip := range service.Spec.ExternalIPs {
				externalIPs = append(externalIPs, ip)
			}
			var externalIPsStr = "<none>"
			if len(externalIPs) > 0 {
				externalIPsStr = strings.Join(externalIPs, ",")
			}

			// 打印输出
			fmt.Printf(printFmt, service.Name, service.Spec.Type, service.Spec.ClusterIP, externalIPsStr,
				strings.Join(servicePorts, ","), time.Now().Sub(service.GetCreationTimestamp().Time).String())
		}
	},
}
